//! @Author: DengLibin 榆霖
//! @Date:  2022-07-05 13:49:58
//! @Des&cription: 



use std::{collections::HashMap, cell::RefCell};

use actix_web::{
    get, HttpResponse, Scope, web::{Data, self}, post,
};

use bcrypt::{hash, DEFAULT_COST};
use common::pojo::ResData;
use dao::{pojo::DbParam, entity::user::User};
use service::user_service;

/// @Author: DengLibin 榆霖
/// @Date:  2022-04-21 11:33:&01
/// @Description: 路由配置
pub fn route() -> Scope{
    info!("user_controller配置路由");
    let sys_scope = web::scope("/user");
    sys_scope
    .service(get_page)
    .service(insert)
}

/// @Author: DengLibin 榆霖
/// @Date:  2022-07-06 11:17:02
/// @Description: 分页查询
#[get("/get_page")]
async fn get_page(
    mysql_conn_pool: Data<mysql::Pool>, //连接池，全局参数传过来
    query: web::Query<HashMap<String, String>>, //查询参数
    ) -> HttpResponse {
    //获取查询参数
    let page_str = query.get("page").unwrap();
    let size_str = query.get("size").unwrap();
    let page: i32 = page_str.parse().unwrap();
    let size: i32 = size_str.parse().unwrap();
    //获取连接池
    let p = (*(mysql_conn_pool)).clone();
    //查询参数
    let db_param = DbParam {page: page, size: size, pool: p};
    let p = user_service::get_page(&db_param).unwrap();

    HttpResponse::Ok().json(ResData::success(p)) // <- send response
}

/// @Author: DengLibin 榆霖
/// @Date:  2022-07-06 11:17:13
/// @Description: 添加
#[post("/insert")]
async fn insert(
    id_generator: Data<RefCell<common::utils::IdGenerator>>, //id生成器
    mysql_conn_pool: Data<mysql::Pool>, //连接池，全局参数传过来
    user: web::Json<User>
    
    ) -> HttpResponse {
     //获取连接池
    let p = (*(mysql_conn_pool)).clone();
    let generator = id_generator;
    let mut u = user.to_owned();
    u.id = generator.borrow_mut().next_id();
    u.passwords = hash(u.passwords, DEFAULT_COST).unwrap();
    u.create_by = -1;
    u.update_by = -1;
    u.deleted = false;
    let param = dao::pojo::UserParam { user: u, pool: p};
    let r = user_service::insert(&param);    
    let result = match r {
        Ok(b) => ResData{code: 0, msg: "success", data: b},
        Err(e) => {
            error!("添加用户失败:{}", e);
            ResData::fail("fail", false)
        },
    };
    HttpResponse::Ok().json(result) // <- send response
}




